/**
 * 消息推送模块
 * @type 
 */

Ccay.Component.PushMsg={
	handler:$.Callbacks(),
	dialog:null,
	currTime:0,
	intervalId:0,
	allowGet:true,//是否允许请求新数据
	timerId:0,
	stopFlag:false,
	pushMsgParam : {},// 动态菜单全局参数
	OutAnnouceTime:null,//推送公告，每次间隔1小时推送一次
	listen:function(clear){

		if(clear){
			this.currTime=0; //清空计数器
		}
		//判断当前是否已经存在消息监听事件，如果不存在，则创建一个新的监听
		if(!this.intervalId){
			this.intervalId=setInterval(function(){
				Ccay.Component.PushMsg.stopFlag=false;
				Ccay.Component.PushMsg.getMessage()
			},Ccay.Config.PushMsg.alternation);//Ccay.Config.PushMsg.alternation
		}
	},
	getMessage:function(){
		Ccay.Log.debug("准备处理消息推送.");
		//当前document 失去焦点，则不去请求消息
		var self = Ccay.Component.PushMsg;
		if(document.hasFocus && !document.hasFocus() &&  ( !window.webkitNotifications ||  window.webkitNotifications.checkPermission() ) ){
			//Ccay.Core.log("浏览器没有获得焦点，并且桌面通知不可用，不请求消息。");
			window.clearInterval(self.intervalId);
			self.intervalId = null;
			setTimeout(function(){self.getMessage()},3000);
			return;
		}
		
		if(!this.intervalId){
			self.listen();
		}
		
		//如果当前允许请求，并且请求次数没有达到上线，则立即ajax请求数据
		if( self.allowGet && self.currTime < Ccay.Config.PushMsg.maxTime){
			//Ccay.Core.log("条件满足，准备获取消息。");
			Ccay.Core.ajax({url:Ccay.Config.PushMsg.service,
				sysauto:true,//指定为系统自动操作
				loading:false,
				success:function(msgs){
					var outAnnouceBool = true,//是否推送公告
						outAnnouceTime=Ccay.Component.PushMsg.OutAnnouceTime;
					if(outAnnouceTime && (new Date()).getTime()-outAnnouceTime.getTime()<3600000){
						outAnnouceBool = false;
					}
					// 自定义消息的处理
					Ccay.Config.PushMsg.open && Ccay.Component.PushMsg.handler.fire(msgs);
					var unPushMsg=[], unReadMsg = 0;
		   			Ccay.Component.PushMsg.currTime++;
		   			if(msgs.length > 0){
		   				for(var i=0,msg;msg=msgs[i];i++){
		   					if(msg.messageType == "OutAnnouce" && outAnnouceBool){
		   						Ccay.Component.PushMsg.OutAnnouceTime = new Date();
		   					}else if(msg.messageType == "OutAnnouce" && !outAnnouceBool){
		   						continue;
		   					}
							if(msg.messageFlag <= 2){
								unReadMsg++;
								unPushMsg.push(msg);//将待推送的消息添加到消息列表
							}
						}
						unReadMsg > 0 ?  $("#unReadMsgAccount").html("<label class='ccay-push-message'>"+unReadMsg+"</label>") : $("#unReadMsgAccount").text("");
		   				Ccay.Component.PushMsg.push(unPushMsg,true);
		   			}
		   			//Ccay.Core.log("进入该页面后第{0}次请求消息数据，读取到未读消息总数 {1} 条".formatText(Ccay.Component.PushMsg.currTime,unReadMsg));
				},
				error:function(xhr, textStatus, errorThrown){
					Ccay.Component.PushMsg.error = true;
					Ccay.Log.warn("请求消息推送服务数据，发生异常！不再请求数据: " + xhr.responseText);
					Ccay.Component.PushMsg.stop();
					return true;
				}
			});
	   	}else{
	   		Ccay.Log.debug("消息推送没有启用或者已经到达最大请求次数，本次不请求。");
	   	}
	},
    /**停止获取推送消息
     * 
     */
	stop:function(){
		window.clearInterval(this.intervalId);
		window.clearTimeout(this.timerId);
		this.timerId =this.intervalId=void 0;
		this.stopFlag=true;
	},
	/** 通过弹出框，顺序推送消息，当前一个消息框关闭后，才继续推送下一个消息框
	 * @param {} msgs
	 */
	push:function(msgs,isNewPush){
		//如果不支持webkitNotifications,或者还没有桌面消息框的权限，并且当前窗口文档没有获得焦点，
		//延迟3秒钟后在执行推送消息，下一次会继续检查,直到满足条件，在提示消息框
		if( ( !window.webkitNotifications ||  window.webkitNotifications.checkPermission() ) && (document.hasFocus && !document.hasFocus()) ){
			Ccay.Component.PushMsg.timerId=setTimeout(function(){
				Ccay.Component.PushMsg.push(msgs);
			},3000);
			return;
		}
		//如果设置了中断提示标示，则直接返回，不再继续提示消息
		if(this.stopFlag){
			this.stopFlag=false;
			return;
		}
		//重新推送，清除原有的定时触发器
		this.timerId && window.clearTimeout(this.timerId);
		
		var msg=msgs.pop(),msgsortMsgs=[],win=$(window),dalayHide=Ccay.Config.PushMsg.delayHide,timeoutId;
		if(!msg){
			return;
		}
		this.allowGet=false;//在推送弹出框没有关闭前，关闭请求
		this.dialog && this.dialog.remove();
		var styleStr = msg.messageIco && msg.messageIco.length>10 ? "style=\"overflow:hide;float:left;display:block;background:url('{0}') no-repeat;\"" : "";
		var contextTmpl=msg.messageType && msg.messageType=="OutAnnouce" ? "<div class='ccay-dialog-message'><div class='ccay-dialog-image' " + styleStr + "></div><div class='ccay-dialog-content'>{1}</div><input type='button' id='iknow' class='init i18n'  i18nKey='Ccay.push.msg.iknow'/></div>" :"<div class='ccay-dialog-message'><div class='ccay-dialog-image' " + styleStr + "></div><div class='ccay-dialog-content'>{1}</div></div>";
			contextTmpl=contextTmpl.formatText(msg.messageIco,msg.messageTemplate);
		
		var closeMsg = function (){
			if(msg.readed){
				Ccay.Component.PushMsg.markReaded(msg.messageId);
				var label = $("#unReadMsgAccount").children();
				if(!isNaN(label.text())){
					var num = label.text()*1 - 1
					num > 0 ? label.text(label.text()*1 - 1) : label.remove();
				}
			}
			if(msgs.length==0){
					//如果消息已经推送完成，则开启允许请求标示
					Ccay.Component.PushMsg.allowGet=true;
			}else{
				//否则继续推送消息
				Ccay.Component.PushMsg.timerId=setTimeout(function(){
					Ccay.Component.PushMsg.push(msgs);
				},3000);
			}
		};
		if ((document.hasFocus && !document.hasFocus()) &&  window.webkitNotifications ) {
			var ntfyAllowed = window.webkitNotifications.checkPermission();
		     if (ntfyAllowed== 0) {
		    	// Ccay.Core.log("ready to show in Desktop Notification.");
		    	 var ntfy = window.webkitNotifications.createNotification(msg.messageIco, 
		        		  msg.messageTitle,  $("<div>"+msg.messageTemplate+"</div>").text());
		          ntfy.display = function() {};
		          ntfy.onerror = function() {};
		          ntfy.onclose = function(){
		          	if(msg.readed !== false){
		          		msg.readed = true;
		          	}
		          	closeMsg();
		          };
		          ntfy.onclick = function() {
		          	msg.readed = true;
		          }
		          ntfy.replaceId = 'CcayHomeNotify';	  
		          
		          setTimeout(function(){
		       	   ntfy.cancel();
		       	   if(!msg.readed){
		       	   	  	msg.readed=false;
		       	   }
		          }, dalayHide);		          
		          ntfy.show();     
		          
		          return ;
		    } else  if (ntfyAllowed == 1) {
		    	//Ccay.Core.log("ready to show enabled remind");
		    	
		    	var link = $("#pushmessage_enable");
		    	
		    	if(link.length ==0){
		    		var linkName = $i18n("ccay.common.label.enableDesktopNotify") ;
		    		var linkMsg = $i18n("ccay.common.message.enableDesktopNotify") ;
		    		
		    		$("#pushmessage_a").before(
			    			"<span  id='pushmessage_enable'><a style='color:red' href='javascript:window.webkitNotifications.requestPermission();$(\"#pushmessage_enable\").remove();'>{0}</a> - </span>".format(linkName));
		    		link = $("#pushmessage_enable>a");
		    		link.fadeOut().fadeIn().ccayTip({content:linkMsg,show:true});
		    	} 			    	
		    } else{
			  // Ccay.Core.log("DesktopNotify disabled.");
		   }
		}
			
		var dialog=Ccay.UI.dialog(null,msg.messageTitle,{
			width:230,
			id:"ccay_pushmsg_dialog",
			height:150,
			modal:false,//非模式窗口
			target : null,
			drag:false,//不能拖拽
			fixed:true,
			show:false,//不自动显示
			showFoot:false,
			position:{top:win.height() - 200, left : win.width()-250},
			content:contextTmpl,
			fnBeforeClose:closeMsg
		});
		this.dialog=dialog.css({top:win.height(),left:win.width()-dialog.width()-2}).show()
		.animate({top:win.height()-dialog.height()},500).bind("mouseover",function(){
			//修改数据库标记，为已读
			msg.readed = true;
			window.clearTimeout(timeoutId || 0);
		}).bind("mouseout",function(){
			window.clearTimeout(timeoutId || 0);
			timeoutId=setTimeout(function(){
				dialog.animate({top:win.height()},500,function(){
					dialog.close();
				});
			},dalayHide)
		});
		dialog.find("#iknow").bind("click",function(){
			dialog.close();
			Ccay.Core.ajax({url:"services/ccay/cms/handle/message/{0}".formatURI(msg.bindItems.cmsVO.id),
				loading:false,
				type:"get",
				success:function(msgs){
					
				}
			});
		});
		timeoutId=setTimeout(function(){
			dialog.animate({top:win.height()},500,function(){
				dialog.close();
			});
		},dalayHide)

	
		
	},
	/** 弹出单个消息提示框后，标记该消息为已读*/
	markReaded:function(messageId){
		Ccay.doGet(Ccay.Config.PushMsg.markReadedService.formatText(messageId),null,function(){},null,null,false);
	},
	view:function(){
		var gridOptions = {
			height : 340,
			wrap : true,
			columns : [
				{field : 'messageTemplate',header : "ccay.cms.label.content",width : 475,content : "${#thisToMessageTemplate(messageFlag,messageTemplate)}",resizable : false ,sortable : false},
				{field : 'creationDate',width : 120,header : "ccay.cms.label.pushDate",cssName : "center",type: 'date',content: "${#thisToDateBefore(data.creationDate)}" ,resizable : false}
			],
			ajax : {
				url : Ccay.Config.PushMsg.viewService
			},
			pagerOp : {
				pageInf : {
					pageSize : 10
				},
				pageSizes : [10]
			}
		}
		
		var dialog;
   		var options={
   			width: 650,
   			height:410,
   			buttons:[{text:"ccay.common.label.close",onClick:function(){dialog.close() }}],
   			content:"<div id='ccayPushMsgDiv'><div style='height:410px;overflow:auto; padding-right:0px;margin:0px;'><div id='msgBody'></div></div></div>".formatValue($i18n("ccay.i18n.label.content"),$i18n("ccay.common.label.creationDate")),
   			fnLoad:function(dlg){
   				Ccay.Component.PushMsg.push([]);
				dlg.find('#msgBody').igrid(gridOptions);
   			}
   		};
   		dialog=Ccay.UI.dialog("","ccay.home.label.mymsg",options);
   		
   		
   		$("#unReadMsgAccount").text("");
   		this.stop();
   		this.allowGet=true;
	},
   /**
    * 消息推送 客户端初始化
    */
	init:function(){
		if(Ccay.Config.PushMsg.open && Ccay.Personalized.global.common.pushMsg.enable!=="0"){
			//设置ajax请求拦截
			Ccay.Core._Delegates.ajax_before.add(function(op){
				if(!op.sysauto){
					var currTime = Ccay.Component.PushMsg.currTime;
					Ccay.Component.PushMsg.currTime=0
					if(currTime >= Ccay.Config.PushMsg.maxTime){
						Ccay.Component.PushMsg.getMessage()
					}else{
						if(!Ccay.Component.PushMsg.error){
							Ccay.Component.PushMsg.listen(true);
						}
					}
					//Ccay.Core.log("监听到到用户请求，将消息推送当前页面的请求数量清零！");
				}
			});
			this.render();
			setTimeout(function(){
				Ccay.Component.PushMsg.listen(true);
				Ccay.Component.PushMsg.getMessage();
			},Ccay.Config.PushMsg.delayLoad)
		}
	},
   /**
    * 在页头浮动区域添加一个菜单项，用来显示我的消息
    * li的id为 liPushMessage
    * a 标签id为 aPushMessage
    * 菜单文本samp id为 pushMessageTitle
    * 维度消息 samp id为  unReadMsgAccount
    */
	render:function(){
		//如果为菜单居顶主题，将消息放到上面显示
		if(Ccay.UI.TopMenu != null){
			liMsg = $("<li title='{0}' class='W3AppTop_li'><span class='W3AppTop_dot' id='pushmessage'  ><a id='pushmessage_a'  href='javascript:Ccay.Component.PushMsg.view();' ><samp  id='pushMessageTitle'>{0}</samp><samp id='unReadMsgAccount' ></samp></a></span></li>".formatValue($i18n("ccay.home.label.mymsg")));
			liMsg.insertAfter($(".W3AppTop_gray_Bar_Content_right ul li:first").next());
		}else{
			var tempdom;
			if($("#appPushMessagePanel").length>0){
				tempdom=$("#appPushMessagePanel");
			}else{
				tempdom=$(".W3AppTop_Header_search_app");
			}
			var liMsg=$("<li title='{0}' ><span class='W3AppTop_dot' id='pushmessage'  ><a id='pushmessage_a'  href='javascript:Ccay.Component.PushMsg.view();' ><samp  id='pushMessageTitle'>{0}</samp><samp id='unReadMsgAccount' ></samp></a></span></li>".formatValue($i18n("ccay.home.label.mymsg")));
			tempdom.append(liMsg);
		}
	}
};

	// 对时间进行格式化处理
	thisToDateBefore = function(data) {
		return Ccay.Format.toDateBefore(data);
	};
	
	//对消息推送内容格式处理
	thisToMessageTemplate = function (data,data1) {
		var messageFlag = (data*1) < 2 ? '<a class=\"ccay-icon status-new\" style=\"cursor:default;\" ></a>' : '';
		return messageFlag+ data1;
	}

// 动态菜单 add by l00195395 2013-4-3
// modified by l00195395 2013-7-12 由原来的方式，现在配置动态菜单时，项目组不需要配置js了
// PushMsg.handler的实现处理
Ccay.Component.PushMsg.handler.add(function(msgs){
	if(msgs.length == 0){
		// 清除全部标识
		$("#leftSiteMapTree").find('.ccay-push-message').remove();
		return;
	};
	var pushMsgParam = Ccay.Component.PushMsg.pushMsgParam;
	for(var i = 0, msg; msg = msgs[i]; i++){
		var msgType = msg.messageType;
		// 动态菜单的全局变量
		if(pushMsgParam[msgType] == null){
			pushMsgParam[msgType] = {
				messageType : msgType,
				messageTitle : 0,
				messageReceiver : null,
				bindEvented : false
			};
		}
		// 消息处理 触发动态菜单
		Ccay.Component.PushMsg.trigger(msg);
	}
});
// 消息处理 触发动态菜单
Ccay.Component.PushMsg.trigger = function(msg){
		var msgType = msg.messageType,
			pushMsgParam = Ccay.Component.PushMsg.pushMsgParam;
		// 条数为0时清除标识
		if(msg.messageTitle == 0){
			$(pushMsgParam[msgType].messageReceiver, $("#leftSiteMapTree, .push-message-container")).each(function(){
				$(this).children('.ccay-push-message').remove();
			});
			// 卸载事件
			$("> li", $("#leftSiteMapTree")).undelegate("click.message." + msgType);
			// 对应的全局变量置空
			pushMsgParam[msgType] = {
				messageType : msgType,
				messageTitle : 0,
				messageReceiver : null,
				bindEvented : false
			};
			return;
		};
		// 推送的消息保存到变量中
		pushMsgParam[msgType].messageReceiver = msg.messageReceiver;
		pushMsgParam[msgType].messageTitle = msg.messageTitle;
		
		// 菜单显示
		$(pushMsgParam[msgType].messageReceiver,  $("#leftSiteMapTree, .push-message-container")).each(function(){
			 var me = $(this);
		     if(me.children('.ccay-push-message').length == 0){
		     	me.append($.create("label", "ccay-push-message").text(pushMsgParam[msgType].messageTitle));
		     }else{
		     	me.children('.ccay-push-message').text(pushMsgParam[msgType].messageTitle);
		     };
		});
		// 菜单节点绑定点击事件,只绑定一次
		if(!pushMsgParam[msgType].bindEvented){
			pushMsgParam[msgType].bindEvented = true;
			$("> li", $("#leftSiteMapTree")).delegate("[treenode_a]","click.message." + msgType, 
			function(){
				// 设置延时，避免点击菜单时，找不到dom
				setTimeout(
					 function(){
					 	$(pushMsgParam[msgType].messageReceiver, $("#leftSiteMapTree")).each(function(){
							var me = $(this);
							if (me.children('.ccay-push-message').length == 0) {
								me.append($.create("label","ccay-push-message").text(pushMsgParam[msgType].messageTitle));
							} else {
								me.children('.ccay-push-message').text(pushMsgParam[msgType].messageTitle);
							};
					    });
					},200);
			});
		}
};

/**
 * 指定获得对应的消息，若无指定则获得全部消息，并处理
 * @param {Array} typeList  类型数组，例如: ["MyTodo","MyWorkspace"]
 * 
 */
Ccay.Component.PushMsg.triggerByName = function(typeList){
	if(Ccay.Config.PushMsg.open){
		var pushMsgParam = Ccay.Component.PushMsg.pushMsgParam;
		// 当指定了具体的消息类型，则获得具体的消息，否则，获得全部的消息
		if(typeList){
			for(var i = 0, type; type = typeList[i]; i++){
				pushMsgParam[type] && pushMsgParam[type].messageReceiver && Ccay.Component.PushMsg.trigger(pushMsgParam[type]);
			}
			return;
		}
		// 遍历全部的消息
		for(var type in pushMsgParam){
			pushMsgParam[type].messageReceiver && Ccay.Component.PushMsg.trigger(pushMsgParam[type]);
		}
	}
};
